package main

//实现加密的
import (
	"bytes"
	"crypto/aes"
	"crypto/cipher"
	"fmt"
	"encoding/base64"
)

func main() {
	src := "110110"
	key := []byte("!@#987321ascwfds")

	fmt.Println("SOURCE!:", src)

	encrypted := AESEncrypt(src, key)
	sEnc := base64.StdEncoding.EncodeToString(encrypted)
	fmt.Println("ENCRYPT:", sEnc)

	decrypted := AESDecrypt(encrypted, key)
	fmt.Println("DECRYPT:", string(decrypted[:]))
}

/**
*
*/
func AESEncrypt(src string, key []byte) []byte {
	block, err := aes.NewCipher(key)
	if err != nil {
		fmt.Println("key error1", err)
	}
	if src == "" {
		fmt.Println("plain content empty")
	}
	// if vi == nil{
	// 	vi = []byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
	// }
	vi := key
	ecb := cipher.NewCBCEncrypter(block, vi)
	content := []byte(src)
	content = PKCS5Padding(content, block.BlockSize())
	crypted := make([]byte, len(content))
	ecb.CryptBlocks(crypted, content)

	return crypted
}

/**
*
*/
func AESDecrypt(crypt []byte, key []byte) []byte {
	block, err := aes.NewCipher(key)
	if err != nil {
		fmt.Println("key error1", err)
	}
	if len(crypt) == 0 {
		fmt.Println("plain content empty")
	}
	//[]byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
	vi := key
	ecb := cipher.NewCBCDecrypter(block, vi)
	decrypted := make([]byte, len(crypt))
	ecb.CryptBlocks(decrypted, crypt)

	return PKCS5Trimming(decrypted)
}

/**
*
*/
func PKCS5Padding(ciphertext []byte, blockSize int) []byte {
	padding := blockSize - len(ciphertext)%blockSize
	padtext := bytes.Repeat([]byte{byte(padding)}, padding)
	return append(ciphertext, padtext...)
}

/**
*
*/
func PKCS5Trimming(encrypt []byte) []byte {
	padding := encrypt[len(encrypt)-1]
	return encrypt[:len(encrypt)-int(padding)]
}